/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.chenweihuacwh.service.baseData;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.javaeye.chenweihuacwh.dao.baseData.MaterialsDAO;
import com.javaeye.chenweihuacwh.dao.procurement.MaterialsRequestDAO;
import com.javaeye.chenweihuacwh.dto.baseData.Materials;
import com.javaeye.chenweihuacwh.web.PageInfo;

public class MaterialsService implements IMaterialsService {
	
	private static Log log = LogFactory.getLog(MaterialsService.class);
	
	private MaterialsDAO dao;
	
	private MaterialsRequestDAO requestDao;
	
	public void setDao(MaterialsDAO dao) {
		this.dao = dao;
	}

	public void setRequestDao(MaterialsRequestDAO requestDao) {
		this.requestDao = requestDao;
	}

	public List<Materials> getAutoCompleteMaterials(String name, int size) {
		List<Materials> results = dao.getAutoCompleteMaterials(name, size);
		if (results == null || results.size() == 0) {
			log.warn("在数据库中未找到物料数据");
		}
		return results;
	}

	@Override
	public Materials getMaterials(String materialsId) {
		int intId = Integer.parseInt(materialsId);
		Materials materials = dao.getMaterials(intId);
		if (materials == null) {
			log.warn("在数据库中未找到指定的物料  id：" + materialsId);
		}
		return materials;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Materials> getMaterialsList(Materials condition, PageInfo pageInfo) {
		List results = dao.getPageData(condition, pageInfo);
		if (results == null || results.size() == 0) {
			log.warn("在数据库中未找到物料数据");
		}
		return results;
	}

	@Override
	public boolean removeMaterials(String materialsId) {
		int intId = Integer.parseInt(materialsId);
		//如果在别的地方使用了就不能删除
		long count = requestDao.getCountByMaterialsId(intId);
		if (count > 0)
			return false;
		
		dao.removeMaterials(intId);
		return true;
	}

	@Override
	public boolean saveMaterials(Materials materials) {
		if (materials.getId() == 0) {
			Materials dbMaterials = dao.getMaterialsByCode(materials.getCode());
			if (dbMaterials != null) {
				return false;
			}
		}
		dao.saveMaterials(materials);
		return true;
	}

}
